package com.jt.www.admin.order_wxb.controller;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.jt.www.admin.order_wxb.service.BatchInsService;
import com.jt.www.enums.woxuebao.InsExcelEnum;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.woxuebao.BatchInsParamVO;
import com.jt.www.model.vo.woxuebao.BatchInsQueryParamVO;
import com.jt.www.model.woxuebao.InsBatchDto;
import com.jt.www.model.woxuebao.InsBatchEntity;
import com.jt.www.util.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author admin_ltf
 * @create 2019-05-18 10:56
 */
@Api(value = "我学保批量投保", tags = {"BATCH-INS-API"}, description = "我学保批量投保")
@RestController
@RequestMapping(value = "/wxb/ins")
public class BatchInsController {

    public static final Logger log = LoggerFactory.getLogger(BatchInsController.class);
    @Autowired
    private BatchInsService batchInsService;

    /**
     * 批量投保
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "批量投保", notes = "批量投保", httpMethod = "POST")
    @PostMapping(value = "")
    public ResponseEntity batchIns(@RequestBody BatchInsParamVO vo) {

        if (vo == null) {
            return GenericDataResponse.errorWithMsg("入参不能为空!");
        }

        try {
            return batchInsService.batchIns(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return GenericDataResponse.errorWithMsg("请求失败!");
        }
    }

    /**
     * 批量投保失败，个别重试
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "投保重试", notes = "投保重试", httpMethod = "GET")
    @GetMapping(value = "/retry")
    public ResponseEntity retryIns(@RequestParam("id") String id) {

        if (StringUtils.isEmpty(id)) {
            return GenericDataResponse.errorWithMsg("入参不能为空!");
        }
        return batchInsService.retryIns(id);
    }

    /**
     * 条件查询批量投保结果
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "条件查询批量投保结果", notes = "条件查询批量投保结果", httpMethod = "POST")
    @PostMapping(value = "/query")
    public ResponseEntity<GenericListResponse<InsBatchEntity>> searchAgreeManageInfoByExample(@RequestBody BatchInsQueryParamVO vo) {
        if (vo == null) {
            return GenericListResponse.listNoCount(GenericListResponse.CODE_NG, "参数不能为空!", Lists.newArrayList());
        }
        PageInfo<InsBatchEntity> result = batchInsService.searchBatchInsByExample(vo);
        return GenericListResponse.listAndCount(result.getList(), result.getTotal());
    }

    @ApiOperation(value = "导出线下业务保单列表", notes = "导出线下业务保单列表")
    @GetMapping(value = "/downBatchInsList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downBatchInsList(BatchInsQueryParamVO vo, HttpServletResponse response, HttpServletRequest request) {

        //解析结果
        try {
            List<InsBatchEntity> batchInsList = batchInsService.getBatchInsList(vo);
            List<InsBatchDto> batchInsOutDtoList =
                    batchInsList.stream().map(batchIns -> new InsBatchDto(batchIns)).collect(Collectors.toList());

            ExcelUtils.checkNull(batchInsOutDtoList);


            Map<String, List<InsBatchDto>> beanParams = Maps.newHashMap();
            beanParams.put("items", batchInsOutDtoList);
            //模板位置
            String path = "excel/templates/batchinslist.xls";

            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);
            String fileName = "线下业务保单列表.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据主键查询消息
     */
    @ApiOperation(value = "根据id查询消息", notes = "根据id查询消息", httpMethod = "GET")
    @GetMapping(value = "/getInsById/{id}")
    public ResponseEntity<GenericDataResponse<InsBatchEntity>> searchInsById(@PathVariable("id") Long id) {
        InsBatchEntity insBatchEntity = batchInsService.searchInsById(id);
        return GenericDataResponse.okWithData(insBatchEntity);
    }


    @ApiOperation(value = "下载模板", notes = "下载模板", httpMethod = "GET")
    @GetMapping("/downInsTemplate")
    public void downInsTemplate(@ApiParam(value = "险种类型:" +
            "  \n云南学平险:YNXPX  \n济宁学平险:JNXPX  \n山东省校责险投保清单模板:SDXZ  \n山东临沂校责险投保清单模板:SDLYXZ  \n山东烟台校责险投保清单模板:SDYTXZ   \n山东日照校责险投保清单模板:SDRZXZ" +
            "   \n山东枣庄校责险投保清单模板:SDZZXZ   \n山东威海校责险投保清单模板:SDWHXZ   \n山东济宁校责险投保清单模板:SDJNXZ   \n企业-实责险投保清单模板:QYSZX  \n校责险投保清单模板:XZX" +
            "  \n学校-实责险投保清单模板:XXSZX  \n学生安全责任保险投保清单模板:XSAZ  \n云南省教职工投保清单模板:YNJZG  \n云南省校方综合保障责任保险投保清单模板:YNXF" +
            "  \n云南省校责险投保清单模板:YNXZ  \n延期支付证明模板:DELAY  \n校园食品安全保险:XYSP  \n新校方责任保险投保清单:NEWXZX" +
            "  \n阳泉、长治、晋城、晋中、临汾、运城投保单填写须知:YQZS   \n太原市专属投保单填写须知:TYZS   \n大同、朔州、忻州、吕梁市投保单填写须知:DTZS" +
            "  \n山西省中小学幼儿园校方责任保险投保清单模板：SXYEYXZ", required = true) @RequestParam(required = true, value = "excelEnum") InsExcelEnum excelEnum, HttpServletResponse response, HttpServletRequest request) {

        batchInsService.downInsTemplate(excelEnum, response, request);

    }


}
